﻿<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Import Namespace="Hidistro.Core" %>
<%@ Import Namespace="wnxd.javascript" %>
<%@ Import Namespace="Hidistro.Entities.Sales" %>
<%@ Import Namespace="Hidistro.SqlDal.Sales" %>
<%@ Import Namespace="Hidistro.Entities.Orders" %>
<%@ Import Namespace="Hidistro.SaleSystem.Shopping" %>
<%@ Import Namespace="wnxd.Web" %>
<%@ Import Namespace="Hidistro.Entities.Promotions" %>
<%@ Import Namespace="Hidistro.SaleSystem.Catalog" %>
<%@ Import Namespace="Hidistro.Entities" %>
<%@ Import Namespace="Hidistro.Entities.Store" %>
<%@ Import Namespace="Hidistro.Entities.Members" %>
<%@ Import Namespace="Hidistro.SqlDal.Members" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {

        if (this.Request.HttpMethod == "POST")
        {
            try
            {
                string data = HttpUtility.UrlDecode(this.Request.Form.ToString());
                if (!string.IsNullOrEmpty(data))
                {
                    json OrderInfo = new json(data);
                    if (OrderInfo != js.undefined)
                    {
                        //ShoppingCartInfo cartInfo = JsonToCartInfo(OrderInfo["shoppingCart"]);
                        ShoppingCartInfo cartInfo = (ShoppingCartInfo)OrderInfo["shoppingCart"];
                        OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(cartInfo, (bool)OrderInfo["isGroupBuy"], (bool)OrderInfo["isCountDown"], (bool)OrderInfo["isSignBuy"]);
                        if (orderInfo != null)
                        {
                            BundlingInfo bundlingInfo = null;
                            if ((bool)OrderInfo["isBundling"])
                            {
                                bundlingInfo = ProductBrowser.GetBundlingInfo((int)OrderInfo["bundlingid"]);
                                orderInfo.BundlingID = bundlingInfo.BundlingID;
                                orderInfo.BundlingPrice = bundlingInfo.Price * cartInfo.LineItems[0].Quantity;
                                orderInfo.Points = cartInfo.GetPoint(bundlingInfo.Price);
                            }
                            if (OrderInfo["TaxRate"] != js.undefined)
                            {
                                orderInfo.Tax = (orderInfo.GetTotal() * decimal.Parse((string)OrderInfo["TaxRate"])) / 100M;
                                if ((bool)OrderInfo["isBundling"])
                                {
                                    orderInfo.Tax = (bundlingInfo.Price * decimal.Parse((string)OrderInfo["TaxRate"])) / 100M;
                                }
                            }
                            orderInfo.InvoiceTitle = (string)OrderInfo["InvoiceTitle"];
                            if ((bool)OrderInfo["isGroupBuy"])
                            {
                                GroupBuyInfo productGroupBuyInfo = ProductBrowser.GetProductGroupBuyInfo(cartInfo.LineItems[0].ProductId);
                                orderInfo.GroupBuyId = productGroupBuyInfo.GroupBuyId;
                                orderInfo.NeedPrice = productGroupBuyInfo.NeedPrice;
                            }
                            if ((bool)OrderInfo["isCountDown"])
                            {
                                CountDownInfo countDownInfo = ProductBrowser.GetCountDownInfo(cartInfo.LineItems[0].ProductId);
                                orderInfo.CountDownBuyId = countDownInfo.CountDownId;
                            }
                            orderInfo.OrderId = (string)OrderInfo["Orderid"];
                            orderInfo.OrderDate = DateTime.Now;
                            orderInfo.UserId = (int)OrderInfo["UserId"];
                            orderInfo.Username = (string)OrderInfo["Username"];
                            orderInfo.EmailAddress = (string)OrderInfo["EmailAddress"];
                            orderInfo.RealName = (string)OrderInfo["RealName"];
                            orderInfo.QQ = (string)OrderInfo["QQ"];
                            orderInfo.Wangwang = (string)OrderInfo["Wangwang"];
                            orderInfo.MSN = (string)OrderInfo["MSN"];
                            orderInfo.Remark = Globals.HtmlEncode((string)OrderInfo["Remark"]);
                            orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
                            orderInfo.RefundStatus = RefundStatus.None;
                            if (OrderInfo["CouponCode"] != js.undefined)
                            {
                                CouponInfo info = ShoppingProcessor.UseCoupon((decimal)OrderInfo["OrderTotal"], (string)OrderInfo["CouponCode"]);
                                if (info != null)
                                {
                                    orderInfo.CouponName = info.Name;
                                    if (info.Amount.HasValue)
                                    {
                                        orderInfo.CouponAmount = info.Amount.Value;
                                    }
                                    orderInfo.CouponCode = (string)OrderInfo["CouponCode"];
                                    orderInfo.CouponValue = info.DiscountValue;
                                }
                            }
                            orderInfo.Address = Globals.HtmlEncode((string)OrderInfo["Address"]);
                            orderInfo.ZipCode = (string)OrderInfo["ZipCode"];
                            orderInfo.ShipTo = Globals.HtmlEncode((string)OrderInfo["ShipTo"]);
                            orderInfo.CellPhone = (string)OrderInfo["Phone"];
                            orderInfo.ShippingModeId = (int)OrderInfo["ShippingModeId"];
                            orderInfo.RegionId = (int)OrderInfo["Region"];
                            orderInfo.ShippingRegion = RegionHelper.GetFullRegion((int)OrderInfo["Region"], "，");
                            orderInfo.ShipToDate = (string)OrderInfo["ShipToDate"];
                            ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(orderInfo.ShippingModeId, true);
                            if (shippingMode != null)
                            {
                                orderInfo.ShippingModeId = shippingMode.ModeId;
                                orderInfo.ModeName = shippingMode.Name;
                                if (!(cartInfo.IsFreightFree || ((cartInfo.LineItems.Count<ShoppingCartItemInfo>(a => !a.IsfreeShipping) <= 0) && (cartInfo.LineGifts.Count <= 0))))
                                {
                                    orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, cartInfo.Weight, shippingMode);
                                }
                                else
                                {
                                    orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
                                }
                            }
                            orderInfo.PaymentTypeId = (int)OrderInfo["PaymentTypeId"];
                            PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(orderInfo.PaymentTypeId);
                            if (paymentMode != null)
                            {
                                orderInfo.PaymentType = Globals.HtmlEncode(paymentMode.Name);
                                orderInfo.PayCharge = ShoppingProcessor.CalcPayCharge(orderInfo.GetTotal(), paymentMode);
                                orderInfo.Gateway = paymentMode.Gateway;
                            }
                            orderInfo.OrderSource =(OrderSource)OrderInfo["OrderSource"];
                            if (ShoppingProcessor.CreatOrder(orderInfo, (string)OrderInfo["Source"]))
                            {
                                orderInfo.OnCreated();
                                if (cartInfo.GetTotalNeedPoint() > 0)
                                {
                                    PointDetailInfo point = new PointDetailInfo
                                    {
                                        OrderId = orderInfo.OrderId,
                                        UserId = orderInfo.UserId,
                                        TradeDate = DateTime.Now,
                                        TradeType = PointTradeType.Change,
                                        Reduced = cartInfo.GetTotalNeedPoint(),
                                        Points = (int)OrderInfo["Points"] - cartInfo.GetTotalNeedPoint()
                                    };
                                    if ((point.Points > 0x7fffffff) || (point.Points < 0))
                                    {
                                        point.Points = 0;
                                    }
                                    new PointDetailDao().AddPointDetail(point);
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                StringBuilder str = new StringBuilder();
                str.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.AppendLine("客户信息：");
                string ip = "";
                if (HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
                {
                    ip = HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
                }
                else
                {
                    ip = HttpContext.Current.Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
                }
                str.AppendLine("连接IP:" + HttpContext.Current.Request.UserHostAddress);
                str.AppendLine("IP:" + ip);
                str.AppendLine("连接主机名:" + HttpContext.Current.Request.UserHostName);
                str.AppendLine("浏览器:" + HttpContext.Current.Request.Browser.Browser);
                str.AppendLine("浏览器版本:" + HttpContext.Current.Request.Browser.MajorVersion.ToString());
                str.AppendLine("操作系统:" + HttpContext.Current.Request.Browser.Platform);
                str.AppendLine("错误信息:");
                str.AppendLine("页面：" + HttpContext.Current.Request.Url.ToString());
                str.AppendLine("错误信息：" + ex.Message);
                str.AppendLine("错误源：" + ex.Source);
                str.AppendLine("异常方法：" + ex.TargetSite);
                str.AppendLine("堆栈信息：" + ex.StackTrace);
                str.AppendLine("--------------------------------------------------------------------------------------------------");
                string upLoadPath = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPath"];
                if (!System.IO.Directory.Exists(upLoadPath))
                {
                    System.IO.Directory.CreateDirectory(upLoadPath);
                }
                string FileName;
                string[] flist = System.IO.Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
                if (flist != null && flist.Length > 0)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileName);
                    if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                    {
                        FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                    }
                }
                else
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
                }
                System.IO.File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
            }
        }
    }
</script>
